package cn.edu.hbpu.common.realms;

import cn.edu.hbpu.pojo.Permission;
import cn.edu.hbpu.pojo.Role;
import cn.edu.hbpu.pojo.Teacher;
import cn.edu.hbpu.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by yuwenteng on 2017/10/11.
 */
public class TeacherRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //通过principalCollection对象获取用户名信息
        String username = (String) principalCollection.getPrimaryPrincipal();
        //调用service层中的方法查询数据库中用户权限信息
        Teacher teacher = loginService.getTeacherInfoByName(username);
        //将权限信息封装到AuthorizationInfo对象中返回
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (teacher != null) {
            for (Role role : teacher.getRoles()) {
                authorizationInfo.addRole(role.getRole());
                for (Permission permission : role.getPermissions()) {
                    authorizationInfo.addStringPermission(permission.getPermission());
                }
            }
        }
        return authorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将authenticationToken强转为UsernamePasswordToken对象
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据token获取username
        String username = token.getUsername();
        //调用service层中的方法查询数据库中用户信息
        Teacher teacher = loginService.getTeacherInfoByName(username);
        AuthenticationInfo authenticationInfo = null;
        if (teacher != null) {
            //构建AuthenticationInfo返回
            authenticationInfo = new SimpleAuthenticationInfo(teacher.getTeacherName(), teacher.getTeacherPassword(), getName());
            //将用户信息存入session
            SecurityUtils.getSubject().getSession().setAttribute("teaInfo", teacher);
        }
        return authenticationInfo;
    }
}
